package com.qing.expert.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qing.expert.common.exception.BusinessException;
import com.qing.expert.modules.admin.entity.Announcement;
import com.qing.expert.modules.admin.mapper.AnnouncementMapper;
import com.qing.expert.modules.admin.service.AnnouncementService;
import com.qing.expert.modules.admin.vo.request.AnnouncementRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Announcement>
        implements AnnouncementService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAnnouncement(AnnouncementRequest request) {
        LocalDateTime now = LocalDateTime.now();
        Announcement announcement = new Announcement()
                .setTitle(request.getTitle())
                .setContent(request.getContent())
                .setSort(request.getSort())
                .setStatus(request.getStatus())
                .setCreateTime(now)
                .setUpdateTime(now);
        save(announcement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAnnouncement(Long id, AnnouncementRequest request) {
        Announcement announcement = getById(id);
        if (announcement == null) {
            throw new BusinessException("通告不存在");
        }

        announcement.setTitle(request.getTitle())
                .setContent(request.getContent())
                .setSort(request.getSort())
                .setStatus(request.getStatus());
        updateById(announcement);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAnnouncement(Long id) {
        removeById(id);
    }

    @Override
    public Page<Announcement> getAnnouncementPage(Integer page, Integer size) {
        return page(new Page<>(page, size), new LambdaQueryWrapper<Announcement>()
                .orderByAsc(Announcement::getSort)
                .orderByDesc(Announcement::getCreateTime));
    }

    @Override
    public Page<Announcement> getHomeAnnouncementList(Integer page, Integer size) {
        return page(new Page<>(page, size), new LambdaQueryWrapper<Announcement>()
                .eq(Announcement::getStatus, 1)
                .orderByAsc(Announcement::getSort)
                .orderByDesc(Announcement::getCreateTime));
    }
}